<script setup lang="ts">
import { onMounted, ref, unref, watch } from 'vue'
import { useBaseApi } from '@/api/base'
import { Delete, Plus } from '@element-plus/icons-vue'

const { GetYearWorkCalendar, PostYearWorkCalendar } = useBaseApi()

interface RowType {
  day: string
  id: string
  is_work: boolean
  month_day: string
  remark: string
  year_month_day: string
}

// 日历加载中（loading 会显示 loading动画）切换年时强制显示加载动画
const loading = ref(false)
// 日历保存中（loadingSave 不会显示 loading动画）为了静默保存
const loadingSave = ref(false)

const calendarRef = ref()
const current = ref(new Date())
const currentYear = ref(new Date().getFullYear())
const items = ref<RowType[]>([])

const onFetch = () => {
  loading.value = true
  const year = current.value.getFullYear()
  GetYearWorkCalendar({ year })
    .then(({ data }) => {
      items.value = data
      currentYear.value = year
    })
    .finally(() => (loading.value = false))
}

const onSave = async () => {
  loadingSave.value = true
  PostYearWorkCalendar({
    year: current.value.getFullYear(),
    rows: unref(items)
  }).finally(() => (loadingSave.value = false))
}

const isDay = (data: any): RowType | undefined => {
  return items.value.find((s) => s.year_month_day === data.day)
}

const onSwitch = (data: any) => {
  if (loadingSave.value) return
  const item = isDay(data)
  if (item) {
    item.is_work = !item.is_work
    onSave()
  }
}

const onDelete = (data: any) => {
  if (loadingSave.value) return
  const index = items.value.findIndex((s) => s.year_month_day === data.day)
  if (index !== -1) {
    items.value.splice(index, 1)
    onSave()
  }
}

const onPlus = (data: any) => {
  if (loadingSave.value) return
  items.value.push({
    day: data.day,
    id: '',
    is_work: [0, 6].includes(data.date.getDay()),
    month_day: data.day.split('-').slice(1).join('-'),
    remark: '',
    year_month_day: data.day
  })
  onSave()
}

const toMonth = (data: any) => {
  return data.date.getMonth() === current.value.getMonth()
}

watch(
  () => current.value,
  () => {
    const year = current.value.getFullYear()
    if (currentYear.value !== year) onFetch()
  }
)

onMounted(() => {
  onFetch()
})
</script>

<template>
  <el-calendar ref="calendarRef" v-model="current" v-loading="loading">
    <template #date-cell="{ data }">
      <div class="flex align-center justify-between" v-if="toMonth(data)">
        <span class="font-bold" :class="{ 'color-danger': [0, 6].includes(data.date.getDay()) }">{{
          data.day.split('-').slice(1).join('-')
        }}</span>
        <div>
          <el-button
            v-if="isDay(data)"
            type="danger"
            text
            circle
            plain
            @click="onDelete(data)"
            :icon="Delete"
          />
          <el-button v-else type="primary" text circle plain @click="onPlus(data)" :icon="Plus" />
        </div>
      </div>
      <div v-if="isDay(data)" class="text-right mt5">
        <el-button type="primary" circle plain v-if="isDay(data)?.is_work" @click="onSwitch(data)"
          >班</el-button
        >
        <el-button type="danger" circle plain v-else @click="onSwitch(data)">休</el-button>
        <br />
      </div>
    </template>
  </el-calendar>
</template>
